<template>
	<el-dialog v-model="visible" :title="!dataForm.id ? '新增' : '编辑'" :close-on-click-modal="false"
	           :close-on-press-escape="false">
		<el-form :model="dataForm" :rules="dataRule" ref="dataFormRef"
		         label-width="120px">
			<el-form-item prop="title" label="标题">
				<el-input v-model="dataForm.title" placeholder="标题"></el-input>
			</el-form-item>
			<el-form-item prop="content" label="内容">
				<el-input :rows="2"
				          type="textarea" v-model="dataForm.content" placeholder="内容"></el-input>
			</el-form-item>
		</el-form>
		<template #footer>
			<el-button @click="visible = false">取消</el-button>
			<el-button type="primary" @click="dataFormSubmitHandle()">确定</el-button>
		</template>
	</el-dialog>
</template>

<script setup>
import debounce from 'lodash/debounce'
import {computed, nextTick, reactive, ref, watch} from "vue";

import http from "../../../utils/request.js";
import {message} from "../../../utils/commonScript.js";

const emit = defineEmits(['refreshDataList'])

const visible = ref(false)
const dataForm = reactive({
	id: '',
	title: '',
	content: ''
})
const dataFormRef = ref()

const dataRule = computed(() => {
	return {
		title: [
			{required: true, message: '必填项不能为空', trigger: 'blur'}
		],
		content: [
			{required: true, message: '必填项不能为空', trigger: 'blur'}
		]
	}
})

const init = (id = '') => {
	visible.value = true
	dataForm.id = id
	nextTick(() => {
		if (dataForm.id) {
			getInfo()
		}
	})
}

// 获取信息
const getInfo = () => {
	http.get(`/app/notice/${dataForm.id}`).then(({data: res}) => {
		if (res.code !== 0) {
			return message.error(res.msg)
		}
		dataForm.title = res.data.title
		dataForm.content = res.data.content

	}).catch(() => {
	})
}
// 表单提交
const dataFormSubmitHandle = debounce(function () {
	dataFormRef.value.validate((valid) => {
		if (!valid) {
			return false
		}
		http[!dataForm.id ? 'post' : 'put']('/app/notice', dataForm).then(({data: res}) => {
			if (res.code !== 0) {
				return message.error(res.msg)
			}
			message({
				message: '操作成功',
				type: 'success',
				duration: 500,
				onClose: () => {
					visible.value = false
					emit('refreshDataList')
				}
			})
		}).catch(() => {
		})
	})
}, 1000, {'leading': true, 'trailing': false})

defineExpose({
	init
})
</script>

<style lang="scss">
</style>
